<?php

namespace Beerus\Modules\Union\Controllers;

use App\Http\Controllers\Controller;
use Biz\cache\wiki\Union as cacheUnion;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $form = new Form(['file' => '']);
        $form->file('file', '订单文件');
        $form->action('/admin/union/order/save');
        return $content
            ->header('上传淘宝客订单')
            ->description(' ')
            ->breadcrumb(
                ['text' => '上传淘宝客订单']
            )
            ->row($form);
    }

    public function save(Request $request)
    {
        try {
            $file = $request->file('file');
            $fileName = '/tmp/tbkOrder-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            if ($res) {
                cacheUnion::add($fileName);
                $success = new MessageBag([
                    'title' => '上传成功'
                ]);
                return redirect('/admin/union/order/index')->with(compact('success'));
            } else {
                throw new \Exception('保存文件失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '上传失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

}